import { ZERODAY } from "../redux/constant";

/*
* 生成唯一 id 标识
*/
export function guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            // eslint-disable-next-line
            v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

/**
 * 防抖（一定时间内只执行一次，不继续进行）
 * @param {防抖函数} fn 
 * @param {延迟时间} delay 
 * @returns 
 */
export const debounce = (fn, delay = 1000) => {
    let timer;
    return function () {
        const context = this
        const args = arguments
        if (timer) {
            clearTimeout(timer)
            timer = null
        }
        timer = setTimeout(() => {
            fn.apply(context, args)
        }, delay)
    }
}

/**
 * 节流（一定时间内只执行一次，但持续执行）
 * @param {节流函数} fn 
 * @param {间隔时间} delay 
 * @returns 
 */
export const thottle = (fn, delay = 1000) => {
    let lastTime = 0;
    return function () {
        const context = this
        const args = arguments
        const currentTime = new Date().getTime()
        if (currentTime - lastTime >= delay) {
            fn.apply(context, args)
            lastTime = currentTime
        }
    }
}

export const formatTime = (time) => {
    if (typeof time !== 'object') {
        return time.split("T")[0]
    } else {
        return time._i.split("T")[0]
    }
}

export const formatTimeLimit = (timeLimit) => {
    if (typeof timeLimit === 'number') {
        return timeLimit === 0 ? <div style={{ color: 'red' }}>{ZERODAY}</div> : timeLimit + "个工作日"
    } else {
        return timeLimit
    }
}

//获取当前日期函数 格式 "2023-09-23"
export const getNowFormatDate = () => {
    let date = new Date(),
        year = date.getFullYear(), //获取完整的年份(4位)
        month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
        strDate = date.getDate() // 获取当前日(1-31)
    if (month < 10) month = `0${month}` // 如果月份是个位数，在前面补0
    if (strDate < 10) strDate = `0${strDate}` // 如果日是个位数，在前面补0
    return `${year}-${month}-${strDate}`
}

// 将moment实例对象转换为 yyyy-mm-dd 日期字符串
export const getTime = (momentObj) => {
    return `${momentObj.get('year')}-${parseInt(momentObj.get('month')) + 1}-${momentObj.get('date')}`
}